package weibo.service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import weibo.model.*;
import weibo.database.*;
import com.alibaba.fastjson.*;

import weibo.tools.HTMLtemplate;
import weibo.tools.saveimage;

/**
 * Servlet implementation class manager
 */
@WebServlet("/manager")
public class manager extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public manager() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		String TYPE=request.getParameter("type");
		HttpSession session=request.getSession(true);
		ManagerData manager=new ManagerData();
		UserDB user=new UserDB();
		TweetDB tweet=new TweetDB();
		JSONObject json=new JSONObject();
		
		String userid=request.getParameter("userid");
		String tweetid=request.getParameter("tweetid");
//		登录
		if (TYPE.equals("login")){
			String username=request.getParameter("username");
			String password=request.getParameter("password");
			boolean Login = manager.Login(username, password);
			if (Login){
				session.setAttribute("manager", username);
				response.getWriter().append("success");
			}else{
				response.getWriter().append("error");
			}
			return;
		}
//		功能
		Object Auth=session.getAttribute("manager");
		if (Auth!=null){
			switch(TYPE){
			case "query.all":
				//查询用户数，点赞数，推文数量
				int[] result=manager.QueryTotal();
				json.put("number",result);
				break;
			case "query.usertweet.total":
				//查询用户和推文的近几天数据
				List<TotalMod> result_user=new ArrayList<TotalMod>();
				result_user=manager.QueryUserTotal();
				json.put("user", result_user);
				List<TotalMod> result_tweet=new ArrayList<TotalMod>();
				result_tweet=manager.QueryTweetTotal();
				json.put("tweet", result_tweet);
				break;
			case "query.user.list":
				//查询用户列表
				List<UserMod> user_list=new ArrayList<UserMod>();
				
				if (userid==null){
					user_list=user.QueryUserInfoNew();
				}else{
					user_list=user.QueryUserInfoCount(Integer.parseInt(userid), 10);
				}
				json.put("user", user_list);
				break;
			case "query.user.user":
				//查询指定用户
				List<UserMod> user_one=new ArrayList<UserMod>();
				user_one=user.QuerySimpleUserInfo(Integer.parseInt(userid));
				json.put("user", user_one);
				break;
			case "query.tweet.tweet":
				//查询指定推文
				List<TweetMod> tweet_one=new ArrayList<TweetMod>();
				tweet_one=tweet.QueryTweet(Integer.parseInt(tweetid));
				json.put("tweet", tweet_one);
				break;
			case "query.tweet.list":
				// 查询推文的列表
				List<TweetMod> tweet_list=new ArrayList<TweetMod>();
				
				if (tweetid==null){
					tweet_list=tweet.QuesyNewTweet();
				}else{
					tweet_list=tweet.QueryAllTweent(Integer.parseInt(tweetid), 10);
				}
				json.put("tweet", tweet_list);
				break;
			case "change.user.password":
				//修改用户密码
				String password=request.getParameter("password");
				boolean res=user.UserChangePassword(Integer.parseInt(userid), password);
				json.put("result",res);
				break;
			case "change.manager.password":
				//修改管理员密码
				String password_m=request.getParameter("password");
				String password_m2=request.getParameter("rollpassword");
				boolean res_m=manager.ChangePassword(Auth.toString(), password_m,password_m2);
				System.out.println(res_m);
				json.put("result",res_m);
				break;
			case "delete.user":
				//删除用户
				boolean res_d=user.DeleteUser(Integer.parseInt(userid));
				json.put("result",res_d);
				break;
			case "delete.tweet":
				//删除推文
				boolean res_t=tweet.DeleteTweet(Integer.parseInt(tweetid));
				json.put("result",res_t);
				break;
			case "editor.add":
				//文章添加
				String html=request.getParameter("html");
				String title=request.getParameter("title");
				
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				
				JSONObject content=new JSONObject();
				content.put("content", html);
				content.put("title", title);
				content.put("auth","管理员");
				content.put("datetime",df.format(new Date()));

				// 模板文件
				ServletContext context = this.getServletContext(); 
				// 生成 html存放位置
				String MURL="D://workspace jee//weibo//WebContent//";
				// 生成文件的名称
				String OUTname=System.currentTimeMillis()+".html";
				//模板替换
				HTMLtemplate temp=new HTMLtemplate(context.getRealPath("/")+"admin\\achtml\\template.html",MURL+"admin\\achtml\\"+OUTname);
				boolean result_template=temp.replaceTemplate(content);
				
				//更新到数据库
				FileDB fd=new FileDB();
				boolean res_fd=fd.CreateFile(OUTname,title);
				
				json.put("result",result_template==res_fd);
				json.put("url","./achtml/"+OUTname);
				break;
			case "editor.show":
				//文章查询
				int fd_page=Integer.parseInt(request.getParameter("page"));
				FileDB fdd=new FileDB();
				List<FileMod> fdd_arr=new ArrayList<FileMod>();
				fdd_arr=fdd.QueryFile(fd_page*10,10*(fd_page+1));
				
				json.put("result", fdd_arr);
				break;
			case "editor.setshow":
				//可见性设置
				int fileid=Integer.parseInt(request.getParameter("id"));
				boolean show_set=Boolean.valueOf(request.getParameter("show")).booleanValue(); 
				FileDB fddd=new FileDB();
				boolean res_fdd=fddd.changeShow(fileid, show_set);
				json.put("result", res_fdd);
				break;
			case "head.set":
				//设置轮播图的内容和图片
				int head_set_id=Integer.parseInt(request.getParameter("id"));
				String head_set_title=request.getParameter("title");
				String head_set_image=request.getParameter("image");
				String head_set_url="head-"+head_set_id+".png";
				
				FileDB head_set=new FileDB();
				
				saveimage head_saveimage=new saveimage(head_set_url,head_set_image);
				boolean head_set_db=head_set.changeHead(head_set_id, head_set_title,head_set_url);
				boolean head_saveimage_boolean=head_saveimage.getFlag();
				json.put("result",head_set_db==head_saveimage_boolean);
				break;
			}
			
			
			
			response.getWriter().append(json.toJSONString());
		}
		
	}

}
